package com.itheima.health.controller;

/**
 * @author zhengjd
 * @date 2020/4/9 20:29
 */

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.constant.RedisMessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * 登录功能
 */
@RestController
@RequestMapping("/login")
public class LoginMobileController {

    @Autowired
    JedisPool jedisPool;

    @Reference
    MemberService memberService;

    @RequestMapping("/check")
    public Result check(HttpServletResponse response, @RequestBody Map map){
        String telephone = (String)map.get("telephone");
        String validateCode =(String) map.get("validateCode");
        Jedis jedis = null;
        try {
            //验证码是否和Redis中一致
            jedis = jedisPool.getResource();
            String redisCode = jedis.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
            if (redisCode == null || !redisCode.equals(validateCode)){
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            } else {
                //用户是否是会员
                Member member = memberService.findByTelephone(telephone);
                //不是会员自动注册
                if (member == null){
                    member = new Member();
                    member.setPhoneNumber(telephone);
                    member.setRegTime(new Date());
                    memberService.add(member);
                }
                //将电话号码存到cookie中
                Cookie cookie = new Cookie("login_member_telephone", telephone);
                cookie.setPath("/"); //路径
                cookie.setMaxAge(30*24*60*60);
                response.addCookie(cookie);
                return new Result(true,MessageConstant.LOGIN_SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,e.getMessage());
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }

    }
}
